import {defineStore} from 'pinia';
import Cookies from 'js-cookie';
import {Session} from '/@/utils/storage';
import {userCenterApi} from "/@/api/user";

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
    state: (): UserInfosState => ({
        userInfos: {
            userName: '',
            photo: '',
            time: 0,
            roles: [],
            authBtnList: [],
        },
    }),
    actions: {
        async setUserInfos() {
            // 存储用户信息到浏览器缓存
            if (Session.get('userInfo')) {
                this.userInfos = Session.get('userInfo');
            } else {
                const userInfos = <UserInfos>await this.getApiUserInfo();
                this.userInfos = userInfos;
            }
        },
        // 模拟接口数据
        // https://gitee.com/lyt-top/vue-next-admin/issues/I5F1HP
        async getApiUserInfo() {

            let adminRoles = ['admin'];
            let testAuthBtnList = ['btn.add', 'btn.del', 'btn.edit', 'btn.link'];
            return userCenterApi().userMain({}).then(res => {

                const userInfos = {
                    userName: res.data.nickname,
                    photo: 'https://img2.baidu.com/it/u=1978192862,2048448374&fm=253&fmt=auto&app=138&f=JPEG?w=504&h=500',
                    time: new Date().getTime(),
                    roles: adminRoles,
                    authBtnList: testAuthBtnList,
                };
                Session.set('userInfo', userInfos);
                return userInfos;
            })


        },
    },
});
